<template>
  <div id="global-header">
    <!-- 全局头部 -->
    <a-row class="grid-demo" style="margin-bottom: 16px;" align="center" :wrap="false">
      <!-- 菜单栏 -->
      <a-col flex="auto">
        <a-menu mode="horizontal" :selected-keys="selectedKeys"  @menu-item-click="handlerMenuClick">
          <a-menu-item key="0" :style="{ padding: 0, marginRight: '38px' }" disabled>
            <div class="titleBar">
              <img class="logo" src="../assets/my.png" alt="">
              <div class="title">智能AI 答题平台</div>
            </div>
          </a-menu-item>
          <a-menu-item v-for="item in visibleRoutes" :key="item.path">{{ item.name }}</a-menu-item>
        </a-menu>
      </a-col>
      <!-- 登录按钮 -->
      <a-col flex="100px">
        <div v-if="loginUserStore.loginUser.id">
          {{ loginUserStore.loginUser.userName || '匿名用户' }}
        </div>
        <a-button v-else type="primary" @click="toLogin">登录</a-button>
      </a-col>
    </a-row>
  </div>   
</template>

<script setup lang="ts">
// 引入路由 循环菜单项
import routes from '@/router/routes'
import { useRouter } from 'vue-router'
import { ref, computed } from 'vue'
import { useLoginUserStore } from '@/store/userStore';
import checkAccess from '@/access/checkAccess';

const router = useRouter()
const loginUserStore = useLoginUserStore()

// 过滤可见菜单 
// 为什么要用computed,如果菜单已经成型,再改变用户登录信息,菜单也不会发生变化
// 除非使用computed,重新计算visibleRoutes
const visibleRoutes = computed(() => {
  return routes.filter((item:any) => {

    //根据meta显示/隐藏过滤菜单栏
    if(item.meta.hideInMenu) {
      return false
    }

    // 根据权限过滤菜单栏
    if(!checkAccess(loginUserStore.loginUser, item.meta.access)) {
      return false
    }

    return true
  })
}) 





// 当前选中菜单项
const selectedKeys = ref([routes[0].path])

// 切换选中菜单
router.afterEach((to) => {
  selectedKeys.value = [to.path]
})

// 菜单跳转
const handlerMenuClick = (key: string) => {
  // selectedKeys.value = [key]
  router.push(key)
}

const toLogin = () => {
  router.push('/user/login')
}

</script>


<style lang="scss" scoped>
.global-header {
  box-sizing: border-box;
  width: 100%;
  padding: 40px;
  background-color: var(--color-neutral-2);
}
.titleBar {
    display: flex;
    align-items: center;
    .title {
      color: #333;
    }
    .logo {
      height: 48px;
      width: auto;
      border-radius: 10px;
      margin-right: 10px;
    }
  }
</style>